<?php
/**
 * Created by PhpStorm.
 * User: 93195
 * Date: 2018/6/20
 * Time: 19:26
 */
class InviteRewardAction extends Action
{
    /**新建或修改邀请奖励
     * @param string $id 修改的时候传
     * @param string $name 名称
     * @param string $status 状态：0-关闭、1-开启
     * @param string $tagId 分组id，用逗号隔开
     * @param string $startTime 有效时间开始时间
     * @param string $endTime 有效时间截止时间
     * @param string $pointSchemeId 对应积分方案id，传的时候必须传id
     */
    public function operateInviteReward(
        $id = '',
        $name = '',
        $status = '',
        $tagId = '',
        $startTime = '',
        $endTime = '',
        $pointSchemeId = ''
    )
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $inviteModel = M('invite_reward');
        $inviteTagModel = M('invite_reward_tag');
        Session::switchCustomer($customerId);

        if ($pointSchemeId > 0 && $id) {
            $res = $inviteModel->where("id = $id")->setField('pointSchemeId', $pointSchemeId);
            if (is_numeric($res)) {
                Output::instance()->object([
                    'code' => 0,
                    'msg' => 'ok'
                ]);
            } else {
                Output::instance()->object([
                    'code' => 1,
                    'msg' => '失败'
                ]);
            }
            return;
        }
        if (!empty($tagId)) $arrTagId = explode(',', $tagId);
        $data = array(
            'cid' => $customerId,
            'name' => $name,
            'status' => $status,
            'startTime' => $startTime,
            'endTime' => $endTime,
            'updateTime' => date('Y-m-d H:i:s', time()),
        );

        if (empty($id)) {
            $data['createTime'] = date('Y-m-d H:i:s', time());
            $res = $inviteModel->add($data);
            if (!empty($arrTagId)) {
                foreach ($arrTagId as $value) {
                    $tagData = [
                        'inviteRewardId' => $res,
                        'tagId' => $value
                    ];
                    $inviteTagModel->add($tagData); //添加标签与方案对应记录
                }
            }
            $inviteId = $res; //前端需要新添加的方案ID
        } else {
            unset($data['createTime']);
            $res = $inviteModel->where("id = $id")->save($data);
            $inviteTagModel->where("inviteRewardId = $id")->delete();
            if (!empty($arrTagId)) {
                foreach ($arrTagId as $value) {
                    $tagData = [
                        'inviteRewardId' => $res,
                        'tagId' => $value
                    ];
                    $inviteTagModel->add($tagData); //添加标签与方案对应记录
                }
            }
            $inviteId = $id;
        }

        if (is_numeric($res)) {
//            $sql = $signInModel->getLastSql();
//            if ($id) {
//                R('Log/add',array('pointScheme','','积分方案',op_update,$sql,'修改积分方案：' . $name));
//            } else {
//                R('Log/add',array('pointScheme','','积分方案',op_add,$sql,'添加积分方案：' . $name));
//            }
            Output::instance()->object([
                'code' => 0,
                'inviteRewardId' => $inviteId,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**邀请奖励列表
     * @param string $name
     * @param string $startTime
     * @param string $endTime
     * @param string $status
     * @param string $tagId
     * @param int $start
     * @param int $limit
     */
    public function inviteRewardList($name = '', $startTime = '', $endTime = '', $status = '', $tagId = '', $start = 0, $limit = 10)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $inviteModel = M('invite_reward');
        $inviteTagModel = M('invite_reward_tag');
        $tagModel = M('invite_tag');
        Session::switchCustomer($customerId);

        /*根据传值组织查询条件*/
        if (!empty($tagId)) {
            $inviteRewardIds = $inviteTagModel->where(['tagId' => $tagId])->getField('inviteRewardId', true);
            $str_inviteRewardIds = implode(',', $inviteRewardIds);
            $where['id'] = ['in', $str_inviteRewardIds];
        }
        if (!empty($startTime) && !empty($endTime)) {
            $start_time = $startTime . ' 00:00:00';
            $end_time = $endTime . ' 23:59:59';
            $where['updateTime'] = ['BETWEEN', [$start_time, $end_time]];
        }
        if (!empty($name)) $where['name'] = ['LIKE', '%' . $name . '%'];
        if (is_numeric($status)) $where['status'] = $status;
        $where['deleted'] = 0;
        $where['cid'] = $customerId;

        $list = $inviteModel->where($where)->order('updateTime desc')->limit($start, $limit)->select();
        /*插入标签信息*/
        foreach ($list as $key => $value) {
            $schemeTagWhere['inviteRewardId'] = $value['id'];
            $tagIds = $inviteTagModel->where($schemeTagWhere)->getField('tagId', true);//获取标签id
            $tagConfigs = [];
            foreach ($tagIds as $tagId) {
                $tagName = $tagModel->where("id = $tagId")->getField('name');
                $tagConfig = ['id' => $tagId, 'name' => $tagName];
                array_push($tagConfigs, $tagConfig);
            }
            $list[$key]['tagConfigs'] = $tagConfigs;//插入标签信息
        }
        $total = $inviteModel->where($where)->count();
        (empty($list)) ? $list=[] : '';
        Output::instance()->object([
            'code' => 0,
            'data' => $list,
            'total' => $total
        ]);
    }

    /**邀请奖励详情
     * @param $id
     */
    public function getInviteRewardById($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $inviteModel = M('invite_reward');
        $inviteTagModel = M('invite_reward_tag');
        $tagModel = M('invite_tag');
        Session::switchCustomer($customerId);

        $result = $inviteModel->where(['id' => $id, 'deleted' => 0])->find();
        $signTagWhere['inviteRewardId'] = $id;
        $tagIds = $inviteTagModel->where($signTagWhere)->getField('tagId', true);
        $tagConfigs = [];
        /*插入标签信息*/
        foreach ($tagIds as $tagId) {
            $tagName = $tagModel->where("id = $tagId")->getField('name');
            $tagConfig = ['id' => $tagId, 'name' => $tagName];
            array_push($tagConfigs, $tagConfig);
        }
        $result['tagConfigs'] = $tagConfigs;

        Output::instance()->object([
            'code' => 0,
            'data' => $result
        ]);
    }

    /**删除邀请奖励
     * @param $id
     */
    public function deleteInviteReward($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $inviteModel = M('invite_reward');
        Session::switchCustomer($customerId);

        $data = [
            'deleted' => 1,
            'deleteTime' => date('Y-m-d H:i:s', time())
        ];
        $res = $inviteModel->where("id = $id")->save($data);

        if (is_numeric($res)) {
//            $sql = $signInModel->getLastSql();
//            $name = $res = $signInModel->where("id = $id")->getField('name');
//            R('Log/add',array('pointScheme','','积分方案',op_delete,$sql,'删除积分方案：' . $name));
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**添加邀请奖励标签
     * @param $name
     */
    public function addInviteTag($name)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('invite_tag');
        Session::switchCustomer($customerId);

        $isHave = $tagModel->where(['name' => $name, 'cid' => $customerId])->find();
        if ($isHave) {
            Output::instance()->object([
                'code' => 1,
                'msg' => '此名称的标签已经存在'
            ]);
            return;
        }
        $data = array(
            'cid' => $customerId,
            'name' => $name,
            'createTime' => date('Y-m-d H:i:s', time())
        );

        $res = $tagModel->add($data);

        if (is_numeric($res)) {
            Output::instance()->object([
                'code' => 0,
                'tagId' => $res,
                'msg' => 'ok'
            ]);
        } else {
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**删除邀请奖励标签
     * @param $id
     */
    public function deleteInviteTag($id)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $inviteTagModel = M('invite_reward_tag');
        $tagModel = M('invite_tag');
        Session::switchCustomer($customerId);

        $tagModel->startTrans();
        $res = $tagModel->where("id = $id")->delete();
        $res2 = $inviteTagModel->where("tagId = $id")->delete();//删除此标签与积分方案的关联关系

        if (is_numeric($res) && is_numeric($res2)) {
            $tagModel->commit();
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok'
            ]);
        } else {
            $tagModel->rollback();
            Output::instance()->object([
                'code' => 1,
                'msg' => '失败'
            ]);
        }
    }

    /**
     * 获取邀请奖励标签
     */
    public function getInviteTag()
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $tagModel = M('invite_tag');
        Session::switchCustomer($customerId);

        $where['cid'] = $customerId;

        $tag = $tagModel->where($where)->select();
        (empty($tag)) ? $tag=[] : '';
        Output::instance()->object($tag);

    }

    /**邀请记录列表
     * @param $id
     * @param string $name
     * @param string $startTime
     * @param string $endTime
     * @param int $start
     * @param int $limit
     */
    public function inviteRecordList($id, $name = '', $startTime = '', $endTime = '', $start = 0, $limit = 10)
    {
        /** 1. 判断用户是否登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*实例化数据库*/
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $recordModel = M('invite_record');
        Session::switchCustomer($customerId);

        if (!empty($name)) $where['u.fullName | i.fullName'] = ['like', '%' . $name . '%'];
        if (!empty($startTime) && !empty($endTime)) {
            $start_time = $startTime . ' 00:00:00';
            $end_time = $endTime . ' 23:59:59';
            $where['r.time'] = ['BETWEEN', [$start_time, $end_time]];
        }
        $where['r.cid'] = $customerId;
        $where['r.inviteRewardId'] = $id;

        $result = $recordModel->alias('r')
            ->join('wx_' . $customerId . '_user u on u.id = r.userId')
            ->join('wx_' . $customerId . '_user i on i.id = r.inviteUserId')
            ->where($where)
            ->field('r.*, u.fullName, i.fullName as inviterName')
            ->limit($start, $limit)
            ->order('time desc')
            ->select();
        if ($result) {
            foreach ($result as $key => $value) {
                if (!$value['newUserPoint']) $result[$key]['newUserPoint'] = 0;
                if (!$value['subscribePoint']) $result[$key]['subscribePoint'] = 0;
                if (!$value['registerPoint']) $result[$key]['registerPoint'] = 0;
            }
        } else {
            $result = [];
        }

        $total = $recordModel->alias('r')
            ->join('wx_' . $customerId . '_user u on u.id = r.userId')
            ->where($where)
            ->order('time desc')
            ->count();

        Output::instance()->object([
            'code' => 0,
            'msg' => 'ok',
            'total' => $total,
            'data' => $result
        ]);
    }
}